package shop;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DeleteProductService implements DeleteProduct{
	private JdbcTemplate db;
	
	@Autowired
	public void setDateSource(DataSource dataSource){
		this.db = new JdbcTemplate(dataSource);
	}
	
	public boolean deleteProduct(long ProductID){
		boolean result = false;
		try{
			if(!existProductID(ProductID)){
				db.update("delete product where id = ?", new Object[]{ProductID});
				result = true;
			}else{
				throw new ProductNotFoundException();
			}
		}catch(RuntimeException e){
			throw e;
		}
		return result;
	}
	
	private boolean existProductID(long ProductID){
		return db.queryForInt("select count(*) from product where id = ?", new Object[]{ProductID}) == 0;
	}
}
